<template>
  <div>
    起点：<input type="text" id="serchStart" v-model="serchMapStart" /> 终点：
    <input ref="ipt" type="text" id="serchEnd" v-model="serchMapEnd" />
    <div id="container" style="width: 800px; height: 400px"></div>
    <div id="panel"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      map: null,
      serchMapStart: "", // 起点
      serchMapEnd: "", // 终点
      startLng: "",
      startLat: "",
      endLng: "",
      endlat: "",
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      const that = this;
      this.map = new AMap.Map("container", {
        resizeEnable: false, // 是否可调整大小
      });
      AMap.plugin(
        ["AMap.Driving", "AMap.AutoComplete", "AMap.PlaceSearch"],
        function () {
          // 获取起点经纬度
          let autoCompleteStart = new AMap.AutoComplete({
            // input 为绑定输入提示功能的input的DOM ID
            input: "serchStart",
          });

          let placeSearchStart = new AMap.PlaceSearch({ map: that.map });
          autoCompleteStart.on("select", function (e) {
            const { lng, lat } = e.poi.location;
            that.startLat = lat;
            that.startLng = lng;
          });
          // 获取终点经纬度
          let autoCompleteEnd = new AMap.AutoComplete({
            // input 为绑定输入提示功能的input的DOM ID
            input: "serchEnd",
          });
          let placeSearchEnd = new AMap.PlaceSearch({ map: that.map });
          autoCompleteEnd.on("select", function (e) {
            const { lng, lat } = e.poi.location;
            that.endlat = lat;
            that.endLng = lng;
          });
          const driving = new AMap.Driving({
            map: that.map,
            panel: "panel",
          });
          that.$refs.ipt.addEventListener("blur", function () {
            driving.search(
              new AMap.LngLat(that.startLng, that.startLat),
              new AMap.LngLat(that.endLng, that.endlat),
              function (status, result) {
                // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
                if (status === "complete") {
                  console.log("绘制驾车路线完成");
                } else {
                  console.log("获取驾车数据失败：" + result);
                }
              }
            );
          });
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 800px;
}

#panel {
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}
#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}
#panel .amap-lib-driving {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  overflow: hidden;
}
</style>
